<?php namespace Admin\Controller;
class CateController extends CommonController{
	private $model;
	public function __auto(){
		$this->model=new \Common\Model\Cate;
	}
	public function index(){
		$data=$this->model
			 ->join('type','type_tid','=','tid')
			 ->orderBy('sort','DESC')->get();
		if(!$data){
			View::success("请先去添加分类",u('add'));
		}
		$data=Data::tree($data,'cname','cid','pid');
		View::with('data',$data);
		View::make();
	}
	public function add(){
		if(IS_POST){
			if($this->model->store()){
				View::success("添加成功",U('Cate/index'));
			}
			View::error($this->model->getError());
		}
		// 获取所属类型
		$typeModel=new \Common\Model\Type;
		$type=$typeModel->get();
		p($type);
		View::with('type',$type);
		View::make();
	}
	public function addSon(){
		if(IS_POST){
			if($this->model->store()){
				View::success("添加成功",U('Cate/index'));
			}
			View::error($this->model->getError());
		}
		$cid=Q('get.cid',0,'intval');
		$data=$this->model
			 ->join('type','type_tid','=','tid')
			 ->where("cid={$cid}")->find();
		p($data);
		// exit;
		View::with('data',$data);
		View::make();

	}
	public function edit(){
		$cid=Q('get.cid',0,'intval');
		$cateData=$this->model->getMy($cid);
		if(IS_POST){
			$pid=Q('post.pid');
			// p($pid);
			if($pid != 0){
				$newData=$this->model->where("cid={$pid}")->find();
				// p($newData);
				// exit;
				foreach ($cateData as $v){
					$this->model->where("cid={$v['cid']}")->save(["type_tid"=>$newData['type_tid']]);
				}
			}
			if($this->model->edit()){
				
				View::success("修改成功",U('Cate/index'));
			}
			View::error($this->model->getError());
		}
		$cid=Q('get.cid',0,'intval');
		
		$oldData=$this->model->where("cid={$cid}")->find();
		View::with('oldData',$oldData);
		// p($oldData['pid']);
		//抓取除去自己和自己子集的所有元素
		$cateData=Data::tree($this->model->getNoMy($cid),'cname','cid','pid');
		// p($cateData);
		// exit;
		View::with('cateData',$cateData);
		View::make();
	}
	public function del(){
		// 获取自己的父级id元素
		$cid=Q('get.cid',0,'intval');
		$pid=$this->model->where("cid={$cid}")->pluck('pid');
		// 获取子集的元素,改父级id的pid为自己的pid
		$data=$this->model->where("pid={$cid}")->update(array('pid'=>$pid));
		$this->model->where("cid={$cid}")->delete();
		View::success("删除成功");
		// p($data);
		// p($pid);

	}
}